﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace MendeleyClient.Phone
{
    public class CategoryDataBroker
    {
        CategoryViewModel categoryViewModel;
        WebClient webClient;
        Uri uri = new Uri("http://api.mendeley.com/oapi/documents/categories/?consumer_key=2c3b432027e4d19d95b69c1209b40d2a04e89f620");

        public CategoryDataBroker(CategoryViewModel categoryViewModel)
        {
            this.categoryViewModel = categoryViewModel;
            webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
        }

        public void GetData()
        {
            if (!webClient.IsBusy)
                webClient.DownloadStringAsync(uri);
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var records = CategoryRecord.Parse(e.Result.ToString());
            categoryViewModel.Items.Add(new CategoryItemViewModel() { Id = "0", Name = "All Categories", Slug = "All Categories" });
            foreach (var record in records)
            {
                categoryViewModel.Items.Add(new CategoryItemViewModel() { Id = record.id, Name = record.name, Slug = record.slug });
            }
            categoryViewModel.IsDataLoaded = true;

        }

        private void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
        }
    }
}
